#!/bin/bash
#
# Copyright (c) 2025 Huawei Tech.Co.,Ltd
# All rights reserved.
#
set -e
CUR_DIR=$(readlink -f "$(dirname "$0")")
LOG_FILE="/root/result.log"
cur_path=$(pwd)

CONAN_USER=$3
CONAN_PASSWORD=$4
echo "start to prepare build env"
chmod +x /root/repo/ci-repos/.common_scripts/common.sh
source /root/repo/ci-repos/.common_scripts/common.sh
prepare_conan2 $CONAN_USER $CONAN_PASSWORD
prepare_bingo
prepare_sdk

# 从MR修改文件列表中获取需要编译的组件版本号列表
function get_mr_change_comp_list()
{
    changelist=''
    cfglist=$(git diff HEAD~1 HEAD --name-only -- | grep config.yml) ||:
    if [ -z "${cfglist}" ]; then
        exit 0
    fi
    recipes2=$(git diff HEAD~1 HEAD --name-only -- | grep recipes2) ||:
    export recipes2

    for cfgfile in ${cfglist}; do
        compname=$(echo $cfgfile | awk -F'/' '{print $2}')
        compvers=$(git diff HEAD~1 HEAD -- ${cfgfile} | grep -E '^\+ ' | grep -vE '(versions|folder)' | tr -d '+ :"') ||:
        if [ -z "${compvers}" ]; then
            continue
        fi
        for compver in ${compvers}; do
            changelist=${compname}/${compver},${changelist}
        done
    done
    if [[ $changelist =~ ,$ ]]; then
        changelist=${changelist::-1}
    fi
    export changelist
}

function build()
{
    get_mr_change_comp_list

    # 循环编译各个组件
    IFS=',' read -ra comps <<< "${changelist}"
    for i in "${comps[@]}"; do
        echo "------------编译构建 bingo build -cp $i${recipes2:+@openubmc/stable --conan2} ------------"
        command="bingo build -cp ${i}${recipes2:+@openubmc/stable --conan2}"
        ${command} && ret=0 || ret=$?
        if [ ${ret} -ne 0 ]; then
            exit 1
        fi
        echo "------------编译构建 $i 成功------------"
    done
    exit 0
}

cd ${cur_path}
build